import Cookie from 'js-cookie'
export const state = () => ({
  contentData: [],
  pageSize: 10,
  pageNum: 0,
  contentLoading: false,
  categoryData: [],
  currentCategory: 0,
  isLastPage: false
})

export const mutations = {
  SET_CONTENT_DATA: function (state, contentData) {
    state.contentData = contentData
  },
  SET_CONTENT_LOADING: function (state, contentLoading) {
    state.contentLoading = contentLoading
  },
  SET_CATEGORY_DATA: function (state, categoryData) {
    state.categoryData = categoryData
  },
  SET_CURRENT_CATEGORY: function (state, currentCategory) {
    state.currentCategory = currentCategory
  },
  SET_PAGE_NUM: function (state, pageNum) {
    state.pageNum = pageNum
  },
  SET_IS_LAST_PAGE: function (state, isLastPage) {
    state.isLastPage = isLastPage
  }
}

export const actions = {
  // oper 判断 请求的方式 是 浏览器回退、点击加载更多、访问url初始化数据
  getContentData ({commit}, {category, oper}) {
    let that = this
    // 判断是否是推荐 推荐category=0
    if (category === null || category === undefined || category === '') {
      category = 0
    }
    // 判断category是否改变，改变了说明是url变化就改变当前页为0
    let pageNum = that.state.content.pageNum
    let oldCategory = that.state.content.currentCategory
    if (category !== oldCategory) {
      commit('SET_CURRENT_CATEGORY', category)
      commit('SET_CONTENT_DATA', [])
    }
    // 点击分页
    if (oper === 'more') {
      pageNum = pageNum + 1
      commit('SET_PAGE_NUM', pageNum)
    } else {
      pageNum = 1
      commit('SET_PAGE_NUM', pageNum)
    }
    // 改变为加载状态
    commit('SET_CONTENT_LOADING', true)
    let result = that.state.content.contentData
    that.$axios.post('/content/getList/' + that.state.content.pageSize + '/' + that.state.content.pageNum, {
      category: that.state.content.currentCategory
    }).then(function (data) {
      if (oldCategory === category) {
        // 设置是否是最后一页
        let _d = data.data.list
        if (_d === null || _d === undefined) {
          _d = []
        }
        if (result === null || result === undefined) {
          result = []
        }
        if (oper === 'more') {
          result = result.concat(_d)
        } else {
          result = _d
        }
      } else {
        result = data.data.list
      }
      commit('SET_IS_LAST_PAGE', data.data.isLastPage)
      commit('SET_CONTENT_DATA', result)
      commit('SET_CONTENT_LOADING', false)
    }).catch(function (err) {
      console.log(err)
    })
  },
  async getCategoryData ({commit}) {
    let that = this
    await this.$axios.post('/category/getList/20/0', {}).then(function (data) {
      Cookie.set('category', data.data.list)
      commit('SET_CATEGORY_DATA', data.data.list)
    }).catch(function (err) {
      console.log(err)
    })
  }
}
